<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="30%"
    :before-close="handleClose"
  >
    <el-form ref="ruleForm" :model="formData" :rules="rules" :inline="true" label-width="80px" style="margin-left: 15%" label-position="right" size="small">
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" clearable />
      </el-form-item>
      <el-form-item label="类型" prop="method">
        <el-select v-model="formData.type" placeholder="请选择组织类型">
          <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="父级组织" prop="pid">
        <el-cascader
          v-model="formData.pid"
          :options="treeOrganization"
          :props="{
            expandTrigger: 'hover',
            checkStrictly: true,
            label: 'label',
            value: 'id',
            children: 'children'}"
          placeholder="请选择父级权限"
          :show-all-levels="false"
          filterable
          clearable
          @expand-change="isTree"
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose" v-text="isBtnCloseTitle" />
      <el-button v-show="isEdit !== 'view'" type="primary" @click="SubmitForm" v-text="isBtnConfTitle" />
    </span>
  </el-dialog>
</template>

<script>
import { treeOrganization, viewOrganization, addOrganization, editOrganization, checkOrganizationName, checkOrganizationPid } from '@/api/organization'
export default {
  // 接收父组件传递过来的值
  props: {
    vdialog: {
      type: Boolean,
      default: false
    },
    vtitle: {
      type: String,
      default: ''
    },
    visedit: {
      type: String,
      default: ''
    },
    vformid: {
      // 接收父组件传过来的ID
      type: Number,
      default: 0
    }
  },
  data() {
    const rulesCheckOrganizationName = (rule, value, callback) => {
      if (this.isEdit === 'edit') {
        callback()
      }
      checkOrganizationName({ name: this.formData.name }).then((res) => {
        if (res.exists && res.code === 200) {
          callback(new Error(res.message))
        } else {
          callback()
        }
      })
    }
    const rulesCheckOrganizationPid = (rule, value, callback) => {
      checkOrganizationPid({ name: this.formData.name, pid: this.rulesPid = this.formData.pid.pop() }).then((res) => {
        if (res.exists && res.code === 200) {
          callback(new Error(res.message))
        } else {
          callback()
        }
      })
    }
    return {
      // rulesPid 联级选择器校验附属属性
      rulesPid: '',
      // 控制弹出框的显示与隐藏
      dialogVisible: false,
      title: '',
      isBtnCloseTitle: '',
      isBtnConfTitle: '',
      formData: { name: '', type: '', pid: [] },
      types: [
        { value: '集团', label: '集团' },
        { value: '公司', label: '公司' },
        { value: '部门', label: '部门' },
        { value: '小组', label: '小组' },
        { value: '分组', label: '分组' },
        { value: '其它', label: '其它' }
      ],
      isEdit: '',
      formId: '',
      treeOrganization: [],
      // rules 表单前验证
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' },
          { validator: rulesCheckOrganizationName, trigger: 'blur' }
        ],
        pid: [
          { required: false, message: '请选择父级菜单', trigger: 'blur' },
          { validator: rulesCheckOrganizationPid, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 监听 父组件传递过来的props内的值并改变/赋值
    vdialog() {
      // dialogVisible 弹框的显示与隐藏
      this.dialogVisible = this.vdialog
      if (this.dialogVisible) {
        // formid 数据ID
        this.formid = this.vformid
        // isEdit 表单状态
        this.isEdit = this.visedit
        // title 弹框的标题
        this.title = this.vtitle
        // isTree 获取目录树数据
        this.isTree()
        // 状态判断
        if (this.isEdit === 'add') {
          this.isBtnCloseTitle = '取消'
          this.isBtnConfTitle = '新增'
        } else if (this.isEdit === 'edit') {
          this.isBtnCloseTitle = '取消'
          this.isBtnConfTitle = '编辑'
          this.viewForm()
        }
      }
    }
  },
  created() {
    this.isTree()
  },
  methods: {
    viewForm() {
      viewOrganization(this.formid).then(res => {
        this.formData.name = res.data.name
        this.formData.type = res.data.type
        this.formData.pid = res.data.pid
      })
    },
    SubmitForm() {
      // 表单验证并新增/编辑
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          // 判断目录树是否有数据，有则截取数值 (this.formData.pid[1] 这里改成取最后一个值)
          if (this.formData.pid) {
            this.formData.pid = this.rulesPid
          }
          if (this.isEdit === 'add') {
            this.addForm()
          } else if (this.isEdit === 'edit') {
            this.editForm()
          } else {
            this.$notify.warning({
              type: 'warning',
              title: '警告',
              message: '表单非法操作',
              showClose: true,
              duration: 0
            })
          }
        }
      })
    },
    addForm() {
      addOrganization(this.formData).then((res) => {
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: res.message,
          showClose: true,
          duration: 5 * 1000
        })
        this.isEditStatus()
        // $parent 子组件调用父组件方法
        this.$parent.getList()
      })
    },
    editForm() {
      editOrganization(this.formid, this.formData).then((res) => {
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: res.message,
          showClose: true,
          duration: 5 * 1000
        })
        this.isEditStatus()
        // $parent 子组件调用父组件方法
        this.$parent.getList()
      })
    },
    // 弹出框关闭后的函数
    handleClose(done) {
      // 子组件调用父组件方法，并传递参数 this.$emit('父组件的方法', '传递的参数')
      if (this.isEdit === 'view') {
        this.isEditStatus()
      } else {
        if (this.formData.username) {
          this.$confirm('确认取消/关闭？')
            .then(_ => {
              this.isEditStatus()
              done()
            })
            .catch(_ => {
            })
        } else {
          this.isEditStatus()
        }
      }
    },
    isEditStatus() {
      // this.$refs['form表单里面的ref值'].resetFields()
      this.$refs['ruleForm'].resetFields()
      this.formData = { name: '', type: '', pid: [] }
      this.$emit('changeShow', 'false', 0)
    },
    // 弹出框关闭后的函数
    // cascade 级联选择器 目录树
    isTree() {
      treeOrganization().then((res) => {
        this.treeOrganization = res.data
        this.setDisable(1, this.treeOrganization, 7)
      })
    },
    setDisable(count, data, maxNum) {
      if (count > maxNum) {
        data.forEach(v => {
          v.disabled = true
        })
      } else {
        data.forEach(v => {
          if (v.children && v.children.length) {
            count++
            this.setDisable(count, v.children, maxNum)
          }
        })
      }
    }
    // cascade 级联选择器 目录树
  }
}
</script>
